import re
from rest_framework import serializers
from areas.models import Area

from users.models import Address


class AreasSerializer(serializers.ModelSerializer):
    class Meta:
        model = Area
        fields = ('id', 'name')


class AddressSerializer(serializers.ModelSerializer):
    province = serializers.StringRelatedField(label='省', read_only=True)
    city = serializers.StringRelatedField(label='市', read_only=True)
    district = serializers.StringRelatedField(label='区', read_only=True)

    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    province_id = serializers.IntegerField(label='省ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time','update_time')

    def validate(self, attrs):
        if not re.match(r'^1[3-9]\d{9}$', attrs['mobile']):
            raise serializers.ValidationError('手机号码有误')
        return attrs

    def create(self, validated_data):

        user = self.context['request'].user
        validated_data['user'] = user

        address = super().create(validated_data)

        return address


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)
